<template>
    <!--弹出窗-->
    <modal ref="modal_1"
           :title="title"
           :isCloseConfirm="this.editable"
           :fullscreen="this.fullscreen"
           top="3%"
           width="50%"
           :close-on-click-modal="true"
           @modalOpened="opened"
           @modalClose="closed">


        <avue-form ref="form"
                   :option="option"
                   v-model="form"
                   @submit="onSubmit" >

            <template #supNo v-if="this.editable">
                <el-autocomplete
                        style="width: 100%;"
                        v-model="form.supNo"
                        :fetch-suggestions="querySupplierNo"
                        placeholder="请输入加工商账号"
                        :trigger-on-focus="false"
                        @select="selectSupplierNo"
                        :fit-input-width="true"
                ></el-autocomplete>
            </template>

            <template #supName v-if="this.editable">
                <el-input v-model="form.supName" readonly placeholder="请选择加工商名称" @click="selectSupplierName" />
            </template>

            <template #materialNo v-if="this.editable">
                <el-autocomplete
                        style="width: 100%;"
                        v-model="form.materialNo"
                        :fetch-suggestions="queryMaterialNo"
                        placeholder="请输入物料编号"
                        :trigger-on-focus="false"
                        @select="selectMaterialNo"
                        :fit-input-width="true"
                ></el-autocomplete>
            </template>

            <template #materialName v-if="this.editable">
                <el-input v-model="form.materialName" readonly placeholder="请选择物料名称" @click="selectMaterialName" />
            </template>

            <template #workList v-if="this.editable">
                <el-input v-model="form.workList" readonly placeholder="请选择加工工序" @click="selectWorkList"/>
            </template>
        </avue-form>

        <el-dialog title="请选择工序" append-to-body v-model="box" width="60%">
            <el-tree
                    :default-expand-all="true"
                    :check-strictly="true"
                    :data="workListData"
                    show-checkbox
                    node-key="id"
                    ref="treeMenu"
                    :props="props"
                    @check-change="menuCheck"
                    :render-content="renderContent"
                    highlight-current
                    :default-expanded-keys="defaultChecks"
            >
            </el-tree>
            <template #footer>
                <span class="dialog-footer">
                  <el-button @click="this.box = false">取 消</el-button>
                  <el-button type="primary" @click="calcMaterial">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!--底部按钮块, 默认只有"取消"按钮-->
        <template #footerButton>
            <el-button type="primary" v-if="(permission.work_price_add || permission.work_price_edit) && editable"
                       :loading="btnLoading" @click="this.$refs.form.submit()">保 存
            </el-button>
            <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
        </template>
        <work-list-dialog  ref="workListDialog"  @success="setWorkListDialog"/>
        <select-material  ref="selectMaterial"  @success="setSelectMaterial"/>
        <select-supplier ref="selectSupplierRef" @success="setSupplier"/>
    </modal>
</template>

<script>
    import { getList, getDetail, add, update, remove } from "@/api/anwise/prod/work_price";
    import {getDetail as getDetailMaterial,remoteList as remoteListMaterial} from "@/api/anwise/material/material";
    import {getDetail as getDetailSupplier,remoteList as remoteListSupplier} from "@/api/anwise/supplier";
    import {checkByCalc, workListSelect} from "@/api/anwise/material/bom_list";
    import workListDialog from './work_list_dialog.vue';
    import selectMaterial from './select_material.vue';
    import selectSupplier from './select_supplier.vue';
    import { mapGetters } from "vuex";
    import {Pattern} from "@/utils/validate.js";

    export default {
        components: {
            workListDialog,
            selectMaterial,
            selectSupplier
        },
        data() {
            return {
                title:"生产单价信息",
                emits: ["success"],
                editable: false,
                isCloseConfirm: false,
                fullscreen: false,
                btnLoading: false,
                box:false,
                form: {},
                query: {},
                props: {
                    label: 'nodeName',
                    value: 'id',
                },
                workListData:[],
                defaultChecks:[],
                workList:[],
                workListNodeId:[],
                loading: true,
                option: {
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "加工商账号",
                            prop: "supNo",
                            type: "input",
                            width:130,
                            rules: [{
                                required: true,
                                message: "请输入加工商账号",
                                trigger: "blur"
                            }],
                            // disabled:true,
                        },
                        {
                            label: "加工商名称",
                            prop: "supName",
                            // type: "select",
                            // filterable: true,
                            // dicUrl: "/blade-anwise/supplier/select",
                            // change:	({column,value})=>{this.supManage(value);},
                            // props: {
                            //     label: 'supName',
                            //     value: 'id',
                            // },
                            // dataType: 'string',
                            width:130,
                            rules: [{
                                required: true,
                                message: "请选择加工商名称",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "物料编号",
                            prop: "materialNo",
                            type: "input",
                            width:130,
                            rules: [{
                                required: true,
                                message: "请输入物料编号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "物料名称",
                            prop: "materialName",
                            type: "input",
                            search: true,
                            overHidden: true,
                            sortable: true,
                            width:130,
                            rules: [{
                                required: true,
                                message: "请输入物料名称",
                                trigger: "blur"
                            }],
                        },

                        {
                            label: "客户条码",
                            prop: "barCode",
                            type: "input",
                            disabled:true,
                            search: true,
                            overHidden: true,
                            sortable: true,
                            width:130,
                            // rules: [{
                            //     required: true,
                            //     message: "请输入客户条码",
                            //     trigger: "blur"
                            // }],
                        },
                        {
                            label: "币别",
                            prop: "rmb",
                            type: "select",
                            disabled:true,
                            filterable: true,
                            overHidden: true,
                            sortable: true,
                            width:120,
                            dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                            props: {
                                label: 'dictValue',
                                value: 'dictKey',
                            },
                            dataType: 'string',
                        },
                        {
                            label: "不含税单价",
                            prop: "taxExclusivePrice",
                            type: "number",
                            controls:false,
                            min:0,
                            rules: [{
                                required: true,
                                message: "请输入不含税单价",
                                trigger: "blur"
                            }],
                            width:130,
                        },
                        {
                            label: "加工工序",
                            prop: "workList",
                            type: "textarea",
                            minRows:1,
                            maxRows:4,
                            // span:24,
                            rules: [{
                                required: true,
                                message: "请选择加工工序",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "类别",
                            prop: "materialType",
                            type: "select",
                            disabled:true,
                            filterable:true,
                            sortable: true,
                            width:120,
                            dicUrl: "/blade-system/dict-biz/dictionary?code=material_s_type",
                            props: {
                                label: 'dictValue',
                                value: 'dictKey',
                            },
                            dataType: 'string',
                            rules: [{
                                required: true,
                                message: "请选择类别",
                                trigger: "blur"
                            }],
                        },
                        // {
                        //     label: "是否已审核",
                        //     prop: "isAssign",
                        //     type: "input",
                        //     search: true,
                        //     overHidden: true,
                        //     sortable: true,
                        //     width:130,
                        //     rules: [{
                        //         required: true,
                        //         message: "请输入物料名称",
                        //         trigger: "blur"
                        //     }],
                        // },
                        {
                            label: "生效年月",
                            prop: "activeDate",
                            type: "month",
                            format: "YYYY年MM月",
                            valueFormat: "YYYY-MM-DD",
                            search: true,
                            overHidden: true,
                            sortable: true,
                            width:130,
                            rules: [{
                                required: true,
                                message: "请选择生效年月",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "是否有效",
                            prop: "isActive",
                            type: "select",
                            disabled:true,
                            value:"是",
                            dicData:[
                                {label:"是", value:"是"},
                                {label:"否", value:"否"}],
                            width:130,
                            // value:"是"
                        },
                        // {
                        //     label: "是否已更新",
                        //     prop: "isRenewal",
                        //     type: "input",
                        //     search: true,
                        //     overHidden: true,
                        //     sortable: true,
                        //     width:130,
                        //     rules: [{
                        //         required: true,
                        //         message: "请输入物料名称",
                        //         trigger: "blur"
                        //     }],
                        // },
                        {
                            label: "审核人",
                            prop: "approver",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:130,
                            disabled:true,
                            rules: [{
                                required: false,
                                message: "请输入审核人",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "审核时间",
                            prop: "approverDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD HH:mm:ss',
                            format:'YYYY-MM-DD HH:mm:ss',
                            overHidden: true,
                            sortable: true,
                            width:130,
                            disabled:true,
                            rules: [{
                                required: false,
                                message: "请选择审核时间",
                                trigger: "blur"
                            }],
                        }
                    ]
                },
                data: [],
                ifullscreen:false
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.work_price_add, false),
                    viewBtn: this.validData(this.permission.work_price_view, false),
                    delBtn: this.validData(this.permission.work_price_delete, false),
                    editBtn: this.validData(this.permission.work_price_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
        },
        methods: {
            handleFullScreen() {
                this.ifullscreen = !this.ifullscreen;
            },
            renderContent(h, {data}){
                return h(
                    'span',
                    {
                        style: {
                            color: '#626AEF',
                        },
                    },
                    data.nodeName+" [<"+data.parentNo+">"+data.parentName+"]-("+(data.modelNo || '无工模')+")"
                )
            },
            open(){
                this.workListNodeId.forEach(res=>{
                    this.$refs.treeMenu.setChecked(res, true);
                })
            },
            menuCheck(data, isChecked) {
                if (isChecked) {
                    if (data.parentId) {
                        this.setParentCheck(data.id)
                    }
                } else {
                    this.setChildUncheck(data.id)
                }
            },
            setChildUncheck(id) {
                const node = this.$refs.treeMenu.getNode(id);
                if (node.data.children) {
                    node.data.children.forEach(item => {
                        this.$refs.treeMenu.setChecked(item.id, false);
                        this.setChildUncheck(item.id)
                    })
                }
            },
            setParentCheck(id) {
                const node = this.$refs.treeMenu.getNode(id);
                if (node.data.parentId) {
                    this.$refs.treeMenu.setChecked(node.data.parentId, true);
                    this.setParentCheck(node.data.parentId)
                }
            },
            calcMaterial() {
                this.loading = true;
                const workListCheck = this.$refs.treeMenu.getCheckedNodes(false, true);
                this.form.workList = "";
                this.workListNodeId = [];
                workListCheck.forEach(item => {
                    this.form.workList += item.level+":"+item.nodeName+"-"+item.parentNo+"/";
                    this.workListNodeId.push(item.id)
                });
                if (this.form.workList.length > 0) {
                    this.form.workList = this.form.workList.substring(0, this.form.workList.length-1);
                }
                let workListCount=0;
                this.workList.forEach(res=>{
                    if(res.nodeNo === "工序"){
                        workListCount++;
                    }
                })
                if(workListCheck.length === workListCount){
                    this.form.workList = "全部";
                }
                this.box=false;
            },
            supManage(value){
                if(value){
                    getDetailSupplier(value).then(res=>{
                        if (res.data.success) {
                            let data = res.data.data;
                            this.form.rmb = data.rmb;
                            this.form.deptId = data.deptId;
                            this.form.supName = data.supName;
                            this.form.supNo = data.supNo;
                        }
                    })
                }
            },
            selectMaterialName() {
                this.$refs.selectMaterial.showSelect();
            },
            setSelectMaterial(data){
                getDetailMaterial(data.id).then(res => {
                    if (res.data.success) {
                        let data = res.data.data;
                        this.form.materialNo = data.materialNo;
                        this.form.materialName = data.materialName;
                        this.form.materialType = data.type;
                        this.form.barCode = data.barCode;
                        this.form.workList = "";
                        this.workListNodeId = [];
                    }
                }).catch(err => {
                    this.$message({
                        type: "error",
                        message: "选择物料时发生异常！"
                    });
                })
            },
            selectWorkList() {
                if(this.form.materialNo){
                    // checkByCalc(this.form.materialNo).then(res => {
                    //     if (res.data.success) {
                            workListSelect(this.form.materialNo).then(res =>{
                                if (res.data.success) {
                                    this.workListData = res.data.data.workTree;
                                    this.workList = res.data.data.workList;
                                    // this.workListData.forEach(item => {
                                    //     console.log(item.id)
                                    //     this.defaultChecks.push(item.id);
                                    //     // this.$refs.treeMenu.setChecked(item.id, true);
                                    // })
                                    this.ifullscreen = false;
                                    this.box = true;

                                }
                            })
                    //     } else {
                    //         this.$message.error(res.data.msg || "当前物料Bom结构异常！");
                    //     }
                    // })
                    setTimeout(() =>{
                    this.$nextTick(() => {
                        console.log("this.$refs.treeMenu", this.$refs.treeMenu);
                        this.$refs.treeMenu.setCheckedNodes(this.workList);
                    });
                    },500)


                    // this.$refs.workListDialog.showSelect();
                }else{
                    this.$message({
                        type: "error",
                        message: "请先选择物料编号！"
                    });
                }
            },
            setWorkListDialog(row) {
                if (row) {
                    this.form.workList = row.workName;
                }
            },
            queryMaterialNo(val,cb){
                this.form.materialType = "";
                this.form.barCode = "";
                this.form.materialName = "";
                this.form.workList = "";

                remoteListMaterial(val).then(res => {
                    if (res.data.success) {
                        let materialList = [];
                        res.data.data.forEach(item => {
                            materialList.push({
                                value:item.materialNo +" - "+item.materialName,
                                materialType: item.type,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                            });
                        })
                        cb(materialList);
                    }
                })
            },
            selectMaterialNo(item){
                console.log(item);
                this.form.materialType = item.materialType;
                this.form.barCode = item.barCode;
                this.form.materialNo = item.materialNo;
                this.form.materialName = item.materialName;
            },
            querySupplierNo(val,cb) {
                this.form.supName = "";
                this.form.supId = "";
                const reg = Pattern.number;
                console.log(reg.test(val));
                if (!reg.test(val)) {
                    this.$message({
                        type: "error",
                        message: "加工商账号只能为数字!"
                    });
                    return;
                }

                remoteListSupplier(val,1).then(res => {
                    if (res.data.success) {
                        let customerList = [];
                        res.data.data.forEach(item => {
                            customerList.push({
                                value:item.supNo +" - "+item.supName,
                                supId: item.id,
                                deptId: item.deptId,
                                supNo: item.supNo,
                                supName: item.supName,
                                rmb:item.rmb,
                            });
                        })
                        cb(customerList);
                    }
                })
            },
            selectSupplierNo(item) {
                console.log(item);
                this.form.supId = item.supId;
                this.form.deptId = item.deptId;
                this.form.supNo = item.supNo;
                this.form.supName = item.supName;
                this.form.rmb = item.rmb;
            },
            selectSupplierName() {
                this.$refs.selectSupplierRef.showSelect("加工商");
            },
            setSupplier(row) {
                this.form.supId = row.id;
                this.form.deptId = row.deptId;
                this.form.supNo = row.supNo;
                this.form.supName = row.supName;
                this.form.rmb = row.rmb;
                console.log("row",row);
            },
            onSubmit(form, done) {
                this.btnLoading = true;
                update(form).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.msg || "保存成功!"
                        });
                        setTimeout(() => {
                            this.btnLoading = false;
                            done();
                            this.$refs.modal_1.hide();
                        }, 1000)
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg || "保存失败!"
                        });
                    }
                }).catch(err => {
                    done();
                    this.btnLoading = false;
                })
            },
            show(option) {
                this.title = option.title;
                this.type = option.type;
                if (option.id) {
                    setTimeout(() => {
                        getDetail(option.id).then(res => {
                            if (res.data.success) {
                                if(this.type === 'copy'){
                                    res.data.data.id="";
                                    res.data.data.taxExclusivePrice = "";
                                    res.data.data.activeDate = "";
                                    res.data.data.approver = "";
                                    res.data.data.approverDate = "";
                                }
                                this.form = res.data.data;
                            }
                        })
                    }, 500);
                } else {
                    this.form = {}
                }
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                this.$refs.modal_1.show();
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view","copy"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        if(type === 'copy'){
                            res.data.data.id="";
                            res.data.data.taxExclusivePrice = "";
                            res.data.data.activeDate = "";
                        }
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },
            opened() {
                console.log("opened")
            },
            closed() {
                this.$emit("success");
            }
        }
    };
</script>

<style></style>
